import React, { PureComponent } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { Card, message, Button, Form, Input } from 'antd'
import { connect } from 'dva'
import departmentService from '@/services/department'

@connect()
@Form.create()
class ChangePw extends PureComponent {
  onFinish = e => {
    const { dispatch } = this.props
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (values.newPassword !== values.reNewPassword) {
          message.warning(`新密码两次输入不一致，请修改后提交。`)
        } else {
          departmentService
            .changePW({
              newPassword: values.newPassword,
              oldPassword: values.oldPassword,
              reNewPassword: values.reNewPassword
            })
            .then(res => {
              if (res) {
                message.success(`密码修改成功，请重新登录。`)
                dispatch({
                  type: 'login/logout'
                })
              }
            })
        }
      }
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form

    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Form
            name="basic"
            labelCol={{
              span: 4,
              offset: 4
            }}
            wrapperCol={{
              span: 8
            }}
            onSubmit={this.onFinish}
            autoComplete="off"
          >
            <Form.Item label="旧密码">
              {getFieldDecorator('oldPassword', {
                rules: [{ required: true, message: '请输入旧密码' }]
              })(<Input type="password" placeholder="请输入旧密码" />)}
            </Form.Item>

            <Form.Item label="新密码">
              {getFieldDecorator('newPassword', {
                rules: [{ required: true, message: '请输入新密码' }]
              })(<Input type="password" placeholder="请输入新密码" />)}
            </Form.Item>

            <Form.Item label="重复新密码">
              {getFieldDecorator('reNewPassword', {
                rules: [{ required: true, message: '请重复输入新密码' }]
              })(<Input type="password" placeholder="请重复输入新密码" />)}
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16
              }}
            >
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </PageHeaderWrapper>
    )
  }
}

export default ChangePw
